package simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

//管道处理器 通道读写 管道处理业务
public class NettyServerHander extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("线程名：" + Thread.currentThread().getName());
        System.out.println("server  ctx = " + ctx);
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline();
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端消息:" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址：" + ctx.channel().remoteAddress());
        final long now = System.currentTimeMillis() / 1000;
        //同步
        Thread.sleep(5 * 1000);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,同步延迟" + (System.currentTimeMillis() / 1000 - now) + "秒。", CharsetUtil.UTF_8));
        //异步任务
        //自定义延时任务，在异步任务后面执行
        ctx.channel().eventLoop().schedule(new Runnable() {
            public void run() {
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,自定义任务，延时," + (System.currentTimeMillis() / 1000 - now) + "秒。", CharsetUtil.UTF_8));
            }
        }, 20, TimeUnit.SECONDS);//延迟20秒执行
        ctx.channel().eventLoop().execute(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5 * 1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,异步任务1，延迟," + (System.currentTimeMillis() / 1000 - now) + "秒。", CharsetUtil.UTF_8));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        ctx.channel().eventLoop().execute(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5 * 1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,异步任务2，延迟," + (System.currentTimeMillis() / 1000 - now) + "秒。", CharsetUtil.UTF_8));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端已执行读取", CharsetUtil.UTF_8));
    }

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //数据写入缓存，并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端，读取完毕。", CharsetUtil.UTF_8));

    }

    //处理异常

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
